package com.li.array;

/**
 * @author lirenchun
 */
public class MyArray {
    /**
     * 定义整形数组
     */
    private int[] elements;

    /**
     * 初始化数组长度
     */
    public MyArray(int n) {
        this.elements = new int[n];
    }

    /**
     * 获取数组长度
     *
     * @return
     */
    public int length() {
        return elements.length;
    }

    /**
     * 往数组中添加数字
     *
     * @param element
     */
    public void add(int element) {
        int[] elementsTemp = new int[elements.length + 1];
        for (int i = 0; i < elements.length; i++) {
            elementsTemp[i] = elements[i];
        }
        elementsTemp[elements.length] = element;
        elements = elementsTemp;
    }

    /**
     * 根据index删除数组指点元素
     *
     * @param index
     */
    public void remove(int index) {
        if (index < 0 || index > elements.length - 1) {
            throw new RuntimeException("数组下标越界");
        } else {
            int[] elementsTemp = new int[elements.length - 1];
            for (int i = 0; i < elements.length; i++) {
                if (i < index) {
                    elementsTemp[i] = elements[i];
                } else if (i > index) {
                    elementsTemp[i] = elements[i + 1];
                }
            }
            elements = elementsTemp;
        }
    }

    /**
     * 根据index获取某个下标的值
     *
     * @param index
     * @return
     */
    public int get(int index) {
        if (index < 0 || index > elements.length - 1) {
            throw new RuntimeException("数组下标越界");
        } else {
            return elements[index];
        }
    }
}
